package com.hyk.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.base.Charsets;
import com.hyk.dto.ApiResult;
import com.hyk.entity.User;
import com.hyk.entity.request.UserRequest;
import com.hyk.entity.response.UserExcel;
import com.hyk.entity.response.UserImportListener;
import com.hyk.enums.ApiEnum;
import com.hyk.exception.GlobalException;
import com.hyk.service.IUserService;
import com.hyk.utils.ImageVerificationCode;
import com.hyk.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hyk
 * @since 2021-03-19
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户相关控制器")
@CrossOrigin
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public ApiResult register(@RequestBody UserRequest request){
        userService.register(request);
        return R.ok();
    }

    @PostMapping("/verificationCode")
    @ApiOperation("获取验证码图片")
    public ApiResult verificationCode() throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageVerificationCode.output(ImageVerificationCode.getImage(),outputStream);

        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        String text = ImageVerificationCode.getText();
        redisTemplate.opsForValue().set(uuid,text,60, TimeUnit.SECONDS);


        byte[] bytes = outputStream.toByteArray();
        String encoder = Base64.getEncoder().encodeToString(bytes);
        encoder = "data:image/png;base64,"+encoder;

        Map<String,Object> map = new HashMap<>();
        map.put("encoder",encoder);
        map.put("key",uuid);
        return R.ok(map);

    }

    @PostMapping("/login")
    @ApiOperation("登录")
    public ApiResult login(@RequestBody UserRequest request){
        Map<String,Object> user = userService.login(request);
        return R.ok(user);
    }

    @PostMapping("/update")
    @ApiOperation("修改用户头像信息")
    public ApiResult upload(@RequestBody UserRequest request){
        User user = new User();
        user.setId(request.getId());
        user.setUserImg(request.getUserImg());

        User byId = userService.getById(request.getId());
        if (byId == null){
            throw new GlobalException(ApiEnum.USERNAME_OR_PASSWORD_IS_NULL);
        }else {
            if (byId.getUserStatus()==0){
                user.setUserStatus(1);
            }else {
                user.setUserStatus(0);
            }
        }

        userService.updateById(user);
        return R.ok(user);
    }

    @PostMapping("/list")
    @ApiOperation("用户列表")
    public ApiResult list(@RequestBody UserRequest request){
        IPage<User> user = userService.findListForPage(request);
        return R.ok(user);
    }

    @GetMapping("/export")
    @ApiOperation("导出数据")
    public void export(HttpServletResponse response) throws IOException {

//        request.setSize(10);
//        IPage<User> userIPage = userService.findListForPage(request);

        List<User> list = userService.list();

        List<UserExcel> excelList = list.stream().map(user -> {
            UserExcel userExcel = new UserExcel();
            BeanUtils.copyProperties(user, userExcel);
            userExcel.setId(user.getId().toString());
            return userExcel;
        }).collect(Collectors.toList());

        response.setCharacterEncoding(Charsets.UTF_8.name());
        String fileName = URLEncoder.encode("用户数据导出", Charsets.UTF_8.name());
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), UserExcel.class).sheet("用户数据表").doWrite(excelList);
    }

    @RequestMapping(value = "/import",method = RequestMethod.POST)
    @ApiOperation(value = "导入用户", notes = "传入excel")
    @CrossOrigin
    public ApiResult importUser(MultipartFile file, Integer isCovered) {
        //校验文件类型（是否为一个表格）
        String filename = file.getOriginalFilename();
        if (StringUtils.isEmpty(filename)) {
            throw new RuntimeException("请上传文件!");
        }
        if ((!StringUtils.endsWithIgnoreCase(filename, ".xls") && !StringUtils.endsWithIgnoreCase(filename, ".xlsx"))) {
            throw new RuntimeException("请上传正确的excel文件!");
        }

        //导入操作
        InputStream inputStream;
        try {
            UserImportListener importListener = new UserImportListener(userService);
            inputStream = new BufferedInputStream(file.getInputStream());
            ExcelReaderBuilder builder = EasyExcel.read(inputStream, UserExcel.class, importListener);
            builder.doReadAll();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok();
    }

}
